<template>
  <div class="jsplumb-container">
    <div
      v-for="item in desk"
      :id="item.dataset.id"
      :key="item.dataset.id"
      :style="getWorkstationStyle(item)"
      class="workstation"
      @click="handleClick(item)"
    >
      <div class="title"></div>

      <!-- <div class="title">{{ item.querySelector('.title')?.textContent }}</div> -->
      <!-- <el-button v-popover="popoverRef" v-click-outside="onClickOutside"> Click me </el-button>
      <el-popover ref="popoverRef" trigger="click" title="With title" virtual-triggering persistent>
        <span> Some content </span>
      </el-popover> -->
    </div>
  </div>
</template>

<script lang="ts" setup>
import { nextTick, onMounted, onUnmounted, ref, unref, watch, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { jsPlumb } from 'jsplumb';
import { ClickOutside as vClickOutside } from 'element-plus';
const props = defineProps({
  desk: {
    type: Array,
    required: true
  }
});
const popoverRef = ref();
const onClickOutside = () => {
  unref(popoverRef).popperRef?.delayHide?.();
  // console.log('点击外部', unref(popoverRef).popperRef);
};
const router = useRouter();
const jsPlumbInstance = ref(null);
const cars = new Map();
const tractionRefs = ref([]); // 添加牵车台引用
const PositioningReference = [
  'sand-1', //喷砂间
  'ny-paint-1', //降噪间
  'room-7'
];
const newPos = ref([]);
// 配置参数
const CONFIG = reactive({
  CAR_WIDTH: 70,
  CAR_HEIGHT: 20,
  ANIMATION_DURATION: 5000,
  COLORS: {
    CAR: '#ffffff',
    CAR_BORDER: '#258c93',
    PATH: '#34495e'
  }
});

const handleClick = (item) => {
  //现代浏览器支持dataset属性，它可以方便地访问所有data-*自定义属性
  if (['top-paint-1', 'top-paint-2', 'sand-1', 'room-8'].includes(item.dataset.id)) {
    router.push({ path: '/dashboard2' });
  }
};
// 初始化jsPlumb
const initJsPlumb = () => {
  jsPlumbInstance.value = jsPlumb.getInstance({
    Connector: ['Straight'],
    PaintStyle: {
      stroke: 'rgba(64, 224, 208, 0.5)', // 半透明浅蓝绿色
      strokeWidth: 2,
      outlineWidth: 1,
      outlineStroke: 'rgba(0, 0, 0, 0.2)',
      dashstyle: '5 5' // 虚线样式
    },
    EndpointStyle: {
      radius: 6,
      fill: 'rgba(64, 224, 208, 0.5)',
      stroke: 'rgba(0, 0, 0, 0.2)',
      strokeWidth: 1
    },
    HoverPaintStyle: {
      stroke: 'rgba(64, 224, 208, 0.7)',
      strokeWidth: 3
    },
    Container: 'jsplumb-container'
  });

  // 设置默认连接样式
  jsPlumbInstance.value.importDefaults({
    ConnectionsDetachable: false,
    Connector: ['Straight'],
    Anchor: ['Left', 'Right', 'Top', 'Bottom'],
    Endpoint: ['Dot', { radius: 6 }],
    PaintStyle: {
      stroke: 'rgba(64, 224, 208, 0.5)',
      strokeWidth: 2,
      outlineWidth: 1,
      outlineStroke: 'rgba(0, 0, 0, 0.2)',
      dashstyle: '5 5'
    }
  });

  // 注册自定义连接器类型
  jsPlumbInstance.value.registerConnectionType('straight', {
    connector: ['Straight'],
    paintStyle: {
      stroke: 'rgba(64, 224, 208, 0.5)',
      strokeWidth: 2,
      outlineWidth: 1,
      outlineStroke: 'rgba(0, 0, 0, 0.2)',
      dashstyle: '5 5'
    },
    hoverPaintStyle: {
      stroke: 'rgba(64, 224, 208, 0.7)',
      strokeWidth: 3
    },
    endpoint: ['Dot', { radius: 6 }],
    endpointStyle: {
      fill: 'rgba(64, 224, 208, 0.5)',
      stroke: 'rgba(0, 0, 0, 0.2)',
      strokeWidth: 1
    },
    anchors: ['Right', 'Left']
  });
};

// 获取工位样式
const getWorkstationStyle = (deskElement) => {
  const rect = deskElement.getBoundingClientRect();
  const containerRect = document.querySelector('.jsplumb-container').getBoundingClientRect();
  CONFIG.CAR_WIDTH = rect.width;
  CONFIG.CAR_HEIGHT = rect.height;

  return {
    position: 'absolute',
    left: `${rect.left - containerRect.left}px`,
    top: `${rect.top - containerRect.top}px`,
    width: `${rect.width}px`,
    height: `${rect.height}px`,
    backgroundColor: 'rgba(255, 255, 255, 0.1)',
    border: '1px solid rgba(0, 0, 0, 0.1)',
    borderRadius: '4px'
  };
};

// 基准屏幕宽度(小屏幕尺寸)
const baseScreenWidth = 1200;
// 当前屏幕宽度与实际宽度的比例系数
const scaleFactor = window.innerWidth / baseScreenWidth;
// console.log(scaleFactor, 'scaleFactor');

// 创建小车
const createCar = (carData, position) => {
  // console.log('Creating car with id:', carData);
  const carElement = document.createElement('div');
  carElement.id = `car-${carData.id}`;
  carElement.dataset.carId = carData.id;
  carElement.className = 'car';
  carElement.style.width = `calc(100% / 6.2)`;
  carElement.style.height = `calc(100% / 17)`;
  carElement.style.backgroundColor = 'rgba(255, 255, 255, 0.15)';
  carElement.style.borderRadius = '8px';
  carElement.style.position = 'absolute';
  carElement.style.alignItems = 'center';
  carElement.style.justifyContent = 'center';
  carElement.style.fontWeight = '600';
  carElement.style.fontSize = '12px';
  carElement.style.color = 'rgba(255, 255, 255, 0.9)';
  carElement.style.zIndex = '1000';
  carElement.style.backdropFilter = 'blur(5px)';
  // carElement.style.overflow = 'visible';
  carElement.style.transition = 'transform 10s ease, opacity 10s ease';
  carElement.style.transform = 'translateX(0)';
  carElement.style.opacity = '1';
  // 创建 tooltip
  const tooltip = document.createElement('div');
  tooltip.className = 'car-tooltip';
  // 设置tooltip的z-index和position
  tooltip.style.position = 'absolute'; // 或 'relative'
  tooltip.style.zIndex = '1003'; // 比carElement更高

  //   tooltip.style.borderRadius = '4px';
  tooltip.innerHTML = `
  <div class="car-tooltip-content">
    <div><span class="nameTip">工位名称：</span><span class='valueTip'>${carData.position.deskName}</span></div>
    <div><span class="nameTip">wbs:</span><span class='valueTip'>${carData.wbs}</span></div>
    <div><span class="nameTip">作业开始时间：</span><span class='valueTip'>${carData.startTime}</span></div>
    <div><span class="nameTip">工序进度：</span><span class='valueTip'>${carData.progress}%</span></div>
    <div><span class="nameTip">整车进度：</span><span class='valueTip'>${carData.wholeProgress}%</span></div>
    <div><span class="nameTip">下一道工序：</span><span class='valueTip'>${carData.position.nextdeskName}</span></div>
  </div>`;

  // 创建左轮
  const leftWheel = document.createElement('div');
  leftWheel.style.width = '100%';
  leftWheel.style.height = '40%';
  leftWheel.style.fontSize = '1.2rem';
  leftWheel.style.display = 'flex';
  leftWheel.style.justifyContent = 'space-around';
  leftWheel.innerHTML = `<span>${carData.wbs}</span>`;
  leftWheel.style.zIndex = '1001';
  carElement.appendChild(leftWheel);

  // 创建右轮
  const rightWheel = document.createElement('div');
  rightWheel.style.width = '100%';
  rightWheel.style.height = '60%';
  rightWheel.style.display = 'flex';
  rightWheel.style.justifyContent = 'space-around';
  rightWheel.classList = `${carData.type}`; //1车头图片 2车头文字
  rightWheel.style.position = 'relative';
  rightWheel.style.cursor = 'pointer';
  rightWheel.style.zIndex = '1001';

  const maskLayer = document.createElement('div');
  maskLayer.className = 'mask-layer';
  maskLayer.id = `zz${carData.id}`;
  maskLayer.style.position = 'absolute';
  maskLayer.style.top = '0';
  maskLayer.style.right = '0';
  maskLayer.style.width = '100%';
  maskLayer.style.height = '100%';
  maskLayer.style.backgroundColor = 'rgba(0, 0, 0, 0.5)';
  maskLayer.style.zIndex = '1002';
  maskLayer.style.pointerEvents = 'none';

  rightWheel.appendChild(maskLayer);
  carElement.appendChild(rightWheel);

  /**
   * 更新车辆元素和工具提示的位置
   *
   * 该代码块主要完成以下功能：
   * 1. 设置车辆元素的left/top位置
   * 2. 根据车辆位置动态调整工具提示(tooltip)的位置
   *    - 水平方向：根据车辆是否处于特定位置(newPos)来调整工具提示的左右偏移
   *    - 垂直方向：根据车辆是否在特定位置上方来调整工具提示的上下偏移
   */
  // 设置车辆元素的绝对定位坐标,设置初始位置
  carElement.style.left = `${position.left}px`;
  carElement.style.top = `${position.top}px`;

  // 调整工具提示的水平位置：
  // - 如果车辆处于第一个特定位置(newPos[0])，工具提示右偏40px
  // - 如果车辆处于第二个特定位置(newPos[1])，工具提示左偏50px
  // - 其他情况保持与车辆水平对齐
  if (position.left == newPos.value[0].left) {
    tooltip.style.left = `${position.left + 50 * scaleFactor}px`;
  } else if (position.left == newPos.value[1].left) {
    tooltip.style.left = tooltip.style.left = `${position.left - 75 * scaleFactor}px`;
  } else {
    tooltip.style.left = `${position.left}px`;
  }

  // 调整工具提示的垂直位置：
  // - 如果车辆在第三个特定位置(newPos[2])上方，工具提示下偏40px
  // - 否则工具提示上偏108px（避免遮挡车辆）
  if (position.top < newPos.value[2].top) {
    tooltip.style.top = `${position.top + 40 * scaleFactor}px`;
    // tooltip.style.top = `${position.top + 150}px`;
  } else {
    tooltip.style.top = `${position.top - 80 * scaleFactor}px`;
    // tooltip.style.top = `${position.top - 150}px`;
  }

  // const po = document.createElement('div');
  // po.innerHTML = `
  //  <el-popover
  //       class="box-item"
  //       title="Title"
  //       content="Top Right prompts info"
  //       placement="top-end"
  //     >
  //       <template #reference>
  //         ${carElement}
  //       </template>
  //     </el-popover>
  // `;

  document.querySelector('.jsplumb-container').appendChild(tooltip);
  document.querySelector('.jsplumb-container').appendChild(carElement);

  // 鼠标进入/离开显示/隐藏 tooltip
  rightWheel.addEventListener('mouseenter', () => {
    tooltip.style.display = 'block';
  });

  rightWheel.addEventListener('mouseleave', () => {
    tooltip.style.display = 'none';
  });
  // 使小车成为 jsPlumb 端点
  jsPlumbInstance.value.draggable(carElement, {
    grid: [10, 10]
  });
  cars.set(carData.id, {
    element: carElement,
    position: position,
    connections: []
  });

  updateMaskWidth(carData.id, 100 - carData.progress);
  return carElement;
};
const updateMaskWidth = (carId, newWidthPercentage) => {
  const maskElement = document.getElementById(`zz${carId}`);
  if (maskElement) {
    maskElement.style.width = `${newWidthPercentage}%`;
  } else {
    console.warn(`遮罩层 zz${carId} 未找到`);
  }
};
// 添加牵车台引用
const setTractionRef = (ref) => {
  if (ref) {
    tractionRefs.value.push(ref);
  }
};

// 判断是否需要使用牵车台
const needsTractionCar = (startPos, endPos) => {
  // 判断是否需要垂直移动
  const isVerticalMovement = Math.abs(endPos.top - startPos.top) > 10;
  return isVerticalMovement;
};

// 找到最近的牵车台
const findNearestCarTrack = (position, targetElementId) => {
  // 根据目标元素ID确定应该使用哪个牵车台
  const startId = position.id;
  const endId = targetElementId;
  let trackIndex = -1;

  // 检查是否是牵车台位置
  const isTractionPosition = (id) => {
    return id.startsWith('traction');
  };

  // 如果起始位置或目标位置是牵车台，直接返回对应的牵车台
  if (isTractionPosition(startId)) {
    trackIndex = parseInt(startId.split('-')[1]) - 1;
  } else if (isTractionPosition(endId)) {
    trackIndex = parseInt(endId.split('-')[1]) - 1;
  } else {
    // 根据列号选择对应的牵车台
    const startColumn = startId.split('-')[0];
    const endColumn = endId.split('-')[0];

    if (
      startColumn === 'room' ||
      startColumn === 'wood' ||
      startColumn === 'polish' ||
      startColumn === 'sand' ||
      endColumn === 'room' ||
      endColumn === 'wood' ||
      endColumn === 'polish' ||
      endColumn === 'sand'
    ) {
      // 如果起始或目标位置在第1、3列，使用第2线的牵车台
      trackIndex = 0;
    } else if (
      startColumn === 'surface' ||
      startColumn === 'weld' ||
      startColumn === 'handover' ||
      startColumn === 'pass-line' ||
      startColumn === 'dry' ||
      endColumn === 'surface' ||
      endColumn === 'weld' ||
      endColumn === 'handover' ||
      endColumn === 'pass-line' ||
      endColumn === 'dry'
    ) {
      // 如果起始或目标位置在第4、6列，使用第5线的牵车台
      trackIndex = 1;
    }
  }

  if (trackIndex === -1) return null;

  const track = document.querySelectorAll('.carLine')[trackIndex];
  if (!track) return null;

  const rect = track.getBoundingClientRect();
  const containerRect = document.querySelector('.jsplumb-container').getBoundingClientRect();
  return {
    left: rect.left - containerRect.left + rect.width / 2,
    top: rect.top - containerRect.top + rect.height / 2,
    trackIndex
  };
};

// 计算路径
const calculatePath = (startPos, endPos) => {
  // 判断是否需要使用牵车台
  if (!needsTractionCar(startPos, endPos)) {
    // 水平移动：直接移动到目标位置
    return [startPos, endPos];
  }

  // 找到最近的牵车台
  const nearestTrack = findNearestCarTrack(startPos, endPos.id);
  if (!nearestTrack) {
    console.error('No car track found');
    return [startPos, endPos];
  }

  // 垂直移动：先水平移动到牵车台，再垂直移动，最后水平移动到目标位置
  return [
    startPos, // 起始位置
    { left: nearestTrack.left - CONFIG.CAR_WIDTH / 2, top: startPos.top }, // 水平移动到牵车台
    { left: nearestTrack.left - CONFIG.CAR_WIDTH / 2, top: endPos.top }, // 在牵车台内垂直移动到目标高度
    endPos // 水平移动到目标位置
  ];
};

// 绘制路径
const drawPath = (path) => {
  const connections = [];
  const arrowColors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEEAD']; // 彩色箭头颜色

  // 为路径的每一段创建连接线
  for (let i = 0; i < path.length - 1; i++) {
    const start = path[i];
    const end = path[i + 1];

    // 创建临时端点
    const startEndpoint = document.createElement('div');
    startEndpoint.style.position = 'absolute';
    startEndpoint.style.left = `${start.left}px`;
    startEndpoint.style.top = `${start.top}px`;
    startEndpoint.style.width = '1px';
    startEndpoint.style.height = '1px';
    document.querySelector('.jsplumb-container').appendChild(startEndpoint);

    const endEndpoint = document.createElement('div');
    endEndpoint.style.position = 'absolute';
    endEndpoint.style.left = `${end.left}px`;
    endEndpoint.style.top = `${end.top}px`;
    endEndpoint.style.width = '1px';
    endEndpoint.style.height = '1px';
    document.querySelector('.jsplumb-container').appendChild(endEndpoint);

    // 判断移动方向
    const isVertical = start.left === end.left;

    // 创建连接线
    const connection = jsPlumbInstance.value.connect({
      source: startEndpoint,
      target: endEndpoint,
      paintStyle: {
        stroke: 'rgba(64, 224, 208, 0.5)',
        strokeWidth: 2,
        outlineWidth: 1,
        outlineStroke: 'rgba(0, 0, 0, 0.2)',
        dashstyle: '5 5'
      },
      endpoint: ['Dot', { radius: 6 }],
      anchors: isVertical
        ? ['Bottom', 'Top'] // 垂直移动
        : ['Right', 'Left'], // 水平移动
      connector: ['Straight'],
      type: 'straight',
      // 添加多个彩色箭头
      overlays: [
        [
          'Arrow',
          {
            location: 0.2,
            width: 10,
            length: 10,
            foldback: 0.8,
            paintStyle: {
              stroke: arrowColors[0],
              fill: arrowColors[0],
              strokeWidth: 1
            }
          }
        ],
        [
          'Arrow',
          {
            location: 0.5,
            width: 10,
            length: 10,
            foldback: 0.8,
            paintStyle: {
              stroke: arrowColors[1],
              fill: arrowColors[1],
              strokeWidth: 1
            }
          }
        ],
        [
          'Arrow',
          {
            location: 0.8,
            width: 10,
            length: 10,
            foldback: 0.8,
            paintStyle: {
              stroke: arrowColors[2],
              fill: arrowColors[2],
              strokeWidth: 1
            }
          }
        ]
      ]
    });

    connections.push({
      connection,
      startEndpoint,
      endEndpoint
    });
  }

  return connections;
};

// 清理路径
const clearPath = (connections) => {
  connections.forEach(({ connection, startEndpoint, endEndpoint }) => {
    jsPlumbInstance.value.deleteConnection(connection);
    startEndpoint.remove();
    endEndpoint.remove();
  });
};

// 动画小车移动
const animateCar = (car, path, onComplete) => {
  let currentIndex = 0;
  updateMaskWidth(car.element.dataset.carId, 0);

  // console.log('animateCar', console.log('Original Car ID:', document.getElementById(car.element.dataset.carId) ) )
  // 先绘制完整路径
  const pathConnections = drawPath(path);

  const animate = () => {
    if (currentIndex < path.length - 1) {
      const start = path[currentIndex];
      const end = path[currentIndex + 1];
      const startTime = Date.now();

      // 添加移动中的样式
      car.element.classList.add('moving');

      const animateStep = () => {
        const elapsed = Date.now() - startTime;
        const progress = Math.min(elapsed / CONFIG.ANIMATION_DURATION, 1);

        // 计算小车左上角的位置（基于中心点）
        const currentLeft = start.left + (end.left - start.left) * progress - CONFIG.CAR_WIDTH / 2;
        const currentTop = start.top + (end.top - start.top) * progress - CONFIG.CAR_HEIGHT / 2;

        // 更新小车位置
        car.element.style.left = `${currentLeft}px`;
        car.element.style.top = `${currentTop}px`;

        if (progress < 1) {
          requestAnimationFrame(animateStep);
        } else {
          // 移除移动中的样式
          car.element.classList.remove('moving');
          currentIndex++;
          animate();
        }
      };

      animateStep();
    } else {
      // 清理路径
      clearPath(pathConnections);
      if (onComplete) {
        onComplete();
      }
    }
  };

  animate();
};

// 计算元素位置
const calculateElementPosition = (elementId, containerRect) => {
  const isTractionPosition = (id) => id.startsWith('traction');

  let element, rect;
  if (isTractionPosition(elementId)) {
    const trackIndex = parseInt(elementId.split('-')[1]) - 1;
    const track = document.querySelectorAll('.carLine')[trackIndex];
    if (!track) {
      throw new Error(`Track not found for position: ${elementId}`);
    }
    rect = track.getBoundingClientRect();
  } else {
    element = document.getElementById(elementId);
    if (!element) {
      throw new Error(`Element not found: ${elementId}`);
    }
    rect = element.getBoundingClientRect();
  }

  return {
    left: rect.left - containerRect.left + rect.width / 2,
    top: rect.top - containerRect.top + rect.height / 2,
    id: elementId
  };
};

// 处理水平移动
const handleHorizontalMovement = async (car, startPos, endPos, onComplete) => {
  console.log('Performing horizontal movement');
  const path = [startPos, endPos];
  await new Promise((resolve) => {
    animateCar(car, path, () => {
      console.log('Horizontal movement completed');
      if (onComplete) onComplete();
      resolve();
    });
  });
};

// 处理工位到工位的移动
const handleWorkstationToWorkstation = async (car, startPos, endPos, nearestTrack, tractionRef, onComplete) => {
  console.log('Moving from workstation to workstation');

  // 移动牵车台到起始位置
  const tractionMoved = await tractionRef.moveCar(0, `traction${nearestTrack.trackIndex + 1}-1`, startPos.id);
  if (!tractionMoved) {
    throw new Error('Failed to move traction car to start position');
  }
  console.log('Traction car moved to start position');

  await new Promise((resolve) => setTimeout(resolve, 300));

  // 小车移动到牵车台
  const tractionTrack = document.querySelectorAll('.carLine')[nearestTrack.trackIndex];
  const tractionRect = tractionTrack.getBoundingClientRect();
  const containerRect = document.querySelector('.jsplumb-container').getBoundingClientRect();

  const tractionCenter = {
    left: tractionRect.left - containerRect.left + tractionRect.width / 2,
    top: startPos.top
  };

  await new Promise((resolve) => {
    animateCar(car, [startPos, tractionCenter], () => {
      car.element.style.display = 'none';
      console.log('Car moved to traction center');
      resolve();
    });
  });

  // 牵车台带着小车移动到目标位置
  await tractionRef.moveCar(0, `traction${nearestTrack.trackIndex + 1}-1`, endPos.id, true);
  await new Promise((resolve) => setTimeout(resolve, 300));

  // 小车从牵车台移动到目标位置
  const finalTractionPosition = {
    left: tractionRect.left - containerRect.left + tractionRect.width / 2,
    top: endPos.top
  };

  car.element.style.display = 'flex';
  car.style.width = `calc(100% / 6.2)`;
  car.style.height = `calc(100% / 17)`;
  car.element.style.flexWrap = 'wrap';
  car.element.style.left = `${finalTractionPosition.left - CONFIG.CAR_WIDTH / 2}px`;
  car.element.style.top = `${finalTractionPosition.top - CONFIG.CAR_HEIGHT / 2}px`;
  await Promise.all([
    tractionRef.moveCar(0, `traction${nearestTrack.trackIndex + 1}-1`, endPos.id, false),
    new Promise((resolve) => {
      animateCar(car, [finalTractionPosition, endPos], () => {
        console.log('Car moved to final position');
        if (onComplete) onComplete();
        resolve();
      });
    })
  ]);
};

// 处理牵车台到工位的移动
const handleTractionToWorkstation = async (car, startPos, endPos, isCarryingCar, nearestTrack, tractionRef, onComplete) => {
  console.log('Moving from traction to workstation');
  // const pathToTarget = [startPos, endPos]
  // await new Promise(resolve => {
  //     animateCar(car, pathToTarget, () => {
  //         car.element.style.display = 'none'
  //         console.log('Car moved from traction to workstation')
  //         if (onComplete) onComplete()
  //         resolve()
  //     })
  // })

  if (isCarryingCar) {
    // 牵车台带着小车移动到目标位置
    // await tractionRef.moveCar(0, `traction${nearestTrack.trackIndex + 1}-1`, endPos.id, true)
    // console.log('Traction car moved with car to target position')

    const tractionTrack = document.querySelectorAll('.carLine')[nearestTrack.trackIndex];
    const tractionRect = tractionTrack.getBoundingClientRect();
    const containerRect = document.querySelector('.jsplumb-container').getBoundingClientRect();
    // 小车从牵车台移动到目标位置
    const finalTractionPosition = {
      left: tractionRect.left - containerRect.left + tractionRect.width / 2,
      top: endPos.top
    };

    car.element.style.display = 'flex';
    car.element.style.flexWrap = 'wrap';
    car.element.style.left = `${finalTractionPosition.left - CONFIG.CAR_WIDTH / 2}px`;
    car.element.style.top = `${finalTractionPosition.top - CONFIG.CAR_HEIGHT / 2}px`;

    await Promise.all([
      tractionRef.moveCar(0, `traction${nearestTrack.trackIndex + 1}-1`, endPos.id, false),
      new Promise((resolve) => {
        animateCar(car, [finalTractionPosition, endPos], () => {
          console.log('Car moved to final position');
          if (onComplete) onComplete();
          resolve();
        });
      })
    ]);
  } else {
    // 移动牵车台到起始位置
    const tractionMoved = await tractionRef.moveCar(0, `traction${nearestTrack.trackIndex + 1}-1`, endPos.id);
    if (!tractionMoved) {
      throw new Error('Failed to move traction car to end position');
    }
    console.log('Traction car moved to end position');

    await new Promise((resolve) => setTimeout(resolve, 300));
  }

  if (onComplete) onComplete();
};

// 处理牵车台之间的移动
const handleTractionToTraction = async (tractionRef, nearestTrack, endId, isCarryingCar, onComplete) => {
  console.log('Moving between traction cars');
  if (isCarryingCar) {
    await tractionRef.moveCar(0, `traction${nearestTrack.trackIndex + 1}-1`, endId, true);
    console.log('Traction car moved with car');
  }
  if (onComplete) onComplete();
};

// 处理工位到牵车台的移动
const handleWorkstationToTraction = async (car, startPos, endPos, nearestTrack, tractionRef, onComplete) => {
  console.log('Moving from workstation to traction');

  // 移动牵车台到起始位置
  // const tractionMoved = await tractionRef.moveCar(0, `traction${nearestTrack.trackIndex + 1}-1`, startPos.id)
  // if (!tractionMoved) {
  //     throw new Error('Failed to move traction car to start position')
  // }
  // console.log('Traction car moved to start position')

  // await new Promise(resolve => setTimeout(resolve, 300))

  // 小车移动到牵车台
  const tractionTrack = document.querySelectorAll('.carLine')[nearestTrack.trackIndex];
  const tractionRect = tractionTrack.getBoundingClientRect();
  const containerRect = document.querySelector('.jsplumb-container').getBoundingClientRect();
  const tractionCenter = {
    left: tractionRect.left - containerRect.left + tractionRect.width / 2,
    top: startPos.top
  };

  await new Promise((resolve) => {
    animateCar(car, [startPos, tractionCenter], () => {
      car.element.style.display = 'none';
      console.log('Car moved to traction center');
      resolve();
    });
  });

  // // 牵车台带着小车移动到目标位置
  // 处理小车立即显示
  await tractionRef.moveCar(0, `traction${nearestTrack.trackIndex + 1}-1`, endPos.id, true);
  console.log('Traction car moved with car to target position');

  // const smallCar = car.element.querySelector('.small-car')
  // if (smallCar) {
  //     smallCar.style.display = 'flex'
  // }

  if (onComplete) onComplete();
};

const handleMoveMessage = async (message) => {
  console.log('=== startTestSequence ===');
  console.log('Received message:', message);

  const { carId, startId, endId, isTractionStart, isTractionEnd, isCarryingCar, onComplete } = message;

  try {
    // 获取小车实例
    const car = cars.get(carId);
    if (!car) {
      throw new Error(`Car not found: ${carId}`);
    }
    console.log('Found car:', car);

    // 获取容器位置
    const containerRect = document.querySelector('.jsplumb-container').getBoundingClientRect();

    // 计算起始和目标位置
    const startPos = calculateElementPosition(startId, containerRect);
    const endPos = calculateElementPosition(endId, containerRect);
    console.log('Calculated positions:', { startPos, endPos });

    // 处理水平移动
    if (!needsTractionCar(startPos, endPos)) {
      // 如果startId和endId相等，则不进行移动
      if (startId === endId) {
        if (isTractionStart && isTractionEnd) {
          // 牵车台到牵车台
          console.log('牵车台到牵车台,不更新工位状态');
          if (onComplete) onComplete();
          return;
        }
      } else {
        if (!isTractionStart && !isTractionEnd) {
          // 工位到工位
          console.log('工位到工位,更新工位状态');
          await handleHorizontalMovement(car, startPos, endPos, onComplete);
          return;
        }
      }
    }

    // 获取最近的牵车台
    const nearestTrack = findNearestCarTrack(startPos, endId);
    if (!nearestTrack) {
      throw new Error('No car track found');
    }
    console.log('Found nearest track:', nearestTrack);

    const tractionRef = tractionRefs.value[nearestTrack.trackIndex];
    if (!tractionRef) {
      throw new Error('Traction car reference not found');
    }
    console.log('Found traction reference:', tractionRef);

    // 根据不同场景处理移动
    // 工位到工位
    if (!isTractionStart && !isTractionEnd) {
      await handleWorkstationToWorkstation(car, startPos, endPos, nearestTrack, tractionRef, onComplete);
    } else if (isTractionStart && !isTractionEnd) {
      // 牵车台到工位
      await handleTractionToWorkstation(car, startPos, endPos, isCarryingCar, nearestTrack, tractionRef, onComplete);
    } else if (isTractionStart && isTractionEnd) {
      // 牵车台到牵车台
      await handleTractionToTraction(tractionRef, nearestTrack, endId, isCarryingCar, onComplete);
    } else if (!isTractionStart && isTractionEnd) {
      // 工位到牵车台
      await handleWorkstationToTraction(car, startPos, endPos, nearestTrack, tractionRef, onComplete);
    }
  } catch (error) {
    console.error('Error during car movement:', error);
    throw error;
  } finally {
    console.log('=== endTestSequence ===');
  }
};
const createDrillingIn = (mask, call, position) => {
  //maskiconlast
  const maskElement = document.createElement('div');
  maskElement.className = `${mask}`;
  maskElement.style.position = 'absolute';
  maskElement.style.left = `${position.left}px`;
  maskElement.style.top = `${position.top}px`;
  maskElement.addEventListener('click', () => router.push(`/dashboard2`));
};
//获取车间位置
const getLocation = (deskId) => {
  const deskElement = document.getElementById(deskId);
  if (deskElement) {
    const rect = deskElement.getBoundingClientRect();

    const containerRect = document.querySelector('.jsplumb-container').getBoundingClientRect();
    // 获取车间位置
    const position = {
      left: rect.left - containerRect.left + rect.width / 2 - CONFIG.CAR_WIDTH / 2,
      top: rect.top - containerRect.top + rect.height / 2 - CONFIG.CAR_HEIGHT / 2
    };
    //创建涂装工艺的下钻页面跳转图标
    createDrillingIn('maskiconlast', position);
  }
};
nextTick(() => {
  //创建下钻图标面漆间3 top-paint-1
  // getLocation('top-paint-1');
  // console.log('top-paint-1', '创建下钻图标面漆间3');
});

// 初始化小车
/**
 * 根据车辆数据初始化或添加小车元素
 * @param {Array} carsData - 车辆数据数组，包含车辆信息和位置
 * @param {boolean} isAdd - 是否添加小车，false表示初始化，true表示添加
 * @param {Function} callback - 回调函数，用于在每个小车处理后执行
 */
const initializeCars = (carsData, isAdd = false, callback) => {
  // 清除现有小车
  if (!isAdd) {
    cars.forEach((car) => car.element.remove());
    cars.clear();
  }

  // 等待DOM更新
  nextTick(() => {
    newPos.value = PositioningReference.map((deskId) => {
      const deskElement = document.getElementById(deskId);
      if (deskElement) {
        const rect = deskElement.getBoundingClientRect();

        const containerRect = document.querySelector('.jsplumb-container').getBoundingClientRect();
        // 获取小车的初始位置
        const position = {
          left: rect.left - containerRect.left + rect.width / 2 - CONFIG.CAR_WIDTH / 2,
          top: rect.top - containerRect.top + rect.height / 2 - CONFIG.CAR_HEIGHT / 2
        };
        return position;
      }
    });

    carsData.forEach((carData) => {
      const deskElement = document.getElementById(carData.position.deskId);
      if (deskElement) {
        const rect = deskElement.getBoundingClientRect();

        const containerRect = document.querySelector('.jsplumb-container').getBoundingClientRect();
        // 获取小车的初始位置
        const position = {
          left: rect.left - containerRect.left + rect.width / 2 - CONFIG.CAR_WIDTH / 2,
          top: rect.top - containerRect.top + rect.height / 2 - CONFIG.CAR_HEIGHT / 2
        };

        // 创建小车元素
        createCar(carData, position);
      }
      // 执行回调函数
      if (callback) {
        callback(carData);
      }
    });
  });
};

// 清理
onUnmounted(() => {
  if (jsPlumbInstance.value) {
    jsPlumbInstance.value.reset();
  }
});

// 初始化
onMounted(() => {
  // setRem()
  initJsPlumb();
});

// 监听工位变化
watch(
  () => props.desk,
  () => {
    cars.forEach((car, id) => {
      const deskElement = document.getElementById(car.position.deskId);
      if (deskElement) {
        const rect = deskElement.getBoundingClientRect();
        car.element.style.left = `${rect.left}px`;
        car.element.style.top = `${rect.top - 10}px`;
      }
    });
  },
  { deep: true }
);
const setRem = () => {
  const baseSize = 10; // 设计稿宽度 / 10（如 1920px / 10 = 192）
  const scale = document.documentElement.clientWidth / 1920;
  document.documentElement.style.fontSize = baseSize * Math.min(scale, 2) + 'px';
};
// 暴露方法
defineExpose({
  initializeCars,
  handleMoveMessage,
  setTractionRef
});
</script>

<style scoped>
/* 车头左侧图标 */
:deep(.ctl) {
  background: url('@/assets/carimage/ct.png') center no-repeat !important;
  background-size: 100% 100% !important;
  display: block !important;
}
/* 车身 */
:deep(.cz) {
  background: url('@/assets/carimage/cz.png') center no-repeat !important;
  background-size: 100% 100% !important;
  display: block !important;
}
/* 车头右侧图标 */
:deep(.ctr) {
  background: url('@/assets/carimage/cw.png') center no-repeat !important;
  background-size: 100% 100% !important;
  display: block !important;
}

.jsplumb-container {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
  /* pointer-events: none; */
}

.jsplumb-container canvas {
  pointer-events: auto;
}

.workstation {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  /* pointer-events: none; */
  padding-top: 5px;
}

.workstation .title {
  color: rgba(255, 255, 255, 0.9);
  font-size: 0.5rem;
  font-weight: 500;
  text-align: center;
  margin-bottom: 5px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
  z-index: 15;
  /* pointer-events: none; */
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 90%;
}

.car {
  pointer-events: auto;
  position: absolute;
  z-index: 1000;
  overflow: visible;
}

.car.moving {
  box-shadow: 0 8px 25px rgba(255, 255, 255, 0.2);
  border-color: rgba(255, 255, 255, 0.5);
  background-color: rgba(255, 255, 255, 0.2);
}
:deep(.car-tooltip) {
  /* position: absolute; */
  /* bottom: 100%;
  left: 50%; */
  transform: translate(-20%, 0);

  background: url('@/assets/carimage/carTooltip.png');
  background-size: 100% 100%;
  background-repeat: no-repeat;
  background-position: center;
  color: #ffffff;
  padding: 1.5rem 1.2rem;
  border-radius: 4px;
  white-space: nowrap;
  font-size: 1.2rem;
  z-index: 99999;
  height: 12rem;
  display: none; /* 默认隐藏 */
}
:deep(.car-tooltip-content) {
  .nameTip {
    display: inline-block;
    width: 10rem;
    color: #00eaff;
  }
}
:deep(.maskiconlast) :deep(.maskicon) {
  width: 1.5rem;
  height: 1.5rem;
  position: absolute;
  top: 0rem;
  right: -1.5rem;
  background-image: url('@/assets/lsicon.png');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  border: 1px solid rgba(255, 255, 255, 0.5);
  border-radius: 10%;
  z-index: 9999;
}
</style>
